<template>
    <view :style="themeColor()">
        <swiper :indicator-dots="false" :autoplay="false" :disable-touch="true" :current="step" class="h-screen"
            :duration="300" v-if="detail">
            <swiper-item>
                <scroll-view scroll-y="true" class="bg-page min-h-screen overflow-hidden">
                    <view v-for="(orderDetail, index) in detail.items"
                        class="m-[var(--top-m)] sidebar-margin px-[var(--pad-sidebar-m)] py-[var(--pad-top-m)] rounded-[var(--rounded-big)] bg-white">
                        <view class="flex">
                            <view class="w-[120rpx] h-[120rpx] flex items-center justify-center">
                                <u--image :radius="'var(--goods-rounded-small)'" width="120rpx" height="120rpx"
                                    :src="img(orderDetail.picUrl)" model="aspectFill">
                                    <template #error>
                                        <image
                                            class="w-[120rpx] h-[120rpx] rounded-[var(--goods-rounded-small)] overflow-hidden"
                                            :src="img('static/resource/images/diy/shop_default.jpg')" mode="aspectFill">
                                        </image>
                                    </template>
                                </u--image>
                            </view>
                            <view class="flex-1 w-0 ml-[20rpx]">
                                <view class="text-ellipsis text-[28rpx] leading-normal truncate">
                                    {{ orderDetail.spuName }}</view>
                                <view v-if="orderDetail.properties"
                                    class="mt-[6rpx] text-[24rpx] leading-[1.3] text-[var(--text-color-light9)] truncate">
                                    {{ skuSpecFormat(orderDetail.properties) }}

                                </view>
                            </view>
                        </view>
                    </view>
                    <view
                        class="my-[var(--top-m)] sidebar-margin px-[var(--pad-sidebar-m)] rounded-[var(--rounded-big)] bg-white">
                        <view class="py-[var(--pad-top-m)] flex items-center" v-if="afterType == 'order'"
                            @click="selectRefundType(30)">
                            <view class="flex-1">
                                <view class="text-[30rpx]">撤销订单</view>

                            </view>
                            <text
                                class="nc-iconfont nc-icon-youV6xx text-[28rpx] text-[var(--text-color-light9)]"></text>
                        </view>

                        <!-- <view
                            class="py-[var(--pad-top-m)] flex items-center border-0 !border-t !border-[#f5f5f5] border-solid"
                            @click="selectRefundType(10)">
                            <view class="flex-1">
                                <view class="text-[30rpx]">仅退款</view>

                            </view>
                            <text
                                class="nc-iconfont nc-icon-youV6xx text-[28rpx] text-[var(--text-color-light9)]"></text>
                        </view>
                        <view
                            class="py-[var(--pad-top-m)] flex items-center border-0 !border-t !border-[#f5f5f5] border-solid"
                            @click="selectRefundType(20)">
                            <view class="flex-1">
                                <view class="text-[30rpx]">退货退款</view>
                                <view class="text-[24rpx] mt-[20rpx] text-[var(--text-color-light9)]">已收到货，需退还收到的货物
                                </view>
                            </view>
                            <text
                                class="nc-iconfont nc-icon-youV6xx text-[28rpx] text-[var(--text-color-light9)]"></text>
                        </view> -->
                    </view>
                </scroll-view>
            </swiper-item>
            <swiper-item>
                <scroll-view scroll-y="true" class="bg-page min-h-screen overflow-hidden">

                    <view
                        class="my-[var(--top-m)] sidebar-margin px-[var(--pad-sidebar-m)] rounded-[var(--rounded-big)] bg-white">
                        <view class="py-[var(--pad-top-m)] flex justify-between items-center">
                            <view class="text-[28rpx]">售后类型</view>
                            <view class="flex ml-[auto] items-center h-[30rpx]">
                                <text class="text-[26rpx] truncate max-w-[460rpx]" v-if="formData.way == 30">撤销订单</text>
                                <text class="text-[26rpx] truncate max-w-[460rpx]" v-if="formData.way == 10">仅退款</text>
                                <text class="text-[26rpx] truncate max-w-[460rpx]" v-if="formData.way == 20">退货退款</text>
                                <text class="text-[26rpx] truncate max-w-[460rpx]"
                                    v-if="formData.way == 0">活动奖励退款</text>
                            </view>
                        </view>
                    </view>
                    <view v-if="formData.way != 30"
                        class="my-[var(--top-m)] sidebar-margin px-[var(--pad-sidebar-m)] rounded-[var(--rounded-big)] bg-white">
                        <view class="py-[var(--pad-top-m)] flex justify-between items-center">
                            <view class="text-[28rpx]"> <text class="font-500">退款方式</text>

                            </view>
                            <view class="flex ml-[auto] items-center h-[30rpx]" @click="refundTypePopup = true">
                                <text class="text-[26rpx]  truncate max-w-[460rpx]">{{
                                    refundTypeName || '请选择' }}</text>
                                <text
                                    class="nc-iconfont nc-icon-youV6xx pt-[4rpx] text-[24rpx] text-[var(--text-color-light9)]"></text>
                            </view>

                        </view>
                    </view>

                    <view
                        class="my-[var(--top-m)] sidebar-margin px-[var(--pad-sidebar-m)] rounded-[var(--rounded-big)] bg-white"
                        v-if="formData?.refundItems && formData?.refundItems.length">
                        <view class="py-[var(--pad-top-m)]">
                            <view class="text-[28rpx] flex items-center">
                                <text class="font-500"> {{ formData.way != 30 ? '退款明细' : '撤销支付' }}
                                </text>
                            </view>
                            <view class="mt-[30rpx]">
                                <view class="flex items-center justify-between"
                                    v-for="(item, index) in formData.refundItems" :key="index">
                                    <!-- <view class="self-center w-[34rpx] mr-[10rpx]  h-[60rpx] flex items-center"
                                        @click.stop="selectOnlyGoods(item)">
                                        <text
                                            class="iconfont text-[var(--price-text-color)] text-[34rpx] w-[34rpx] h-[34rpx] rounded-[17rpx] overflow-hidden shrink-0"
                                            :class="{ 'iconxuanze1': item.checked, 'bg-[#F5F5F5]': !item.checked }">
                                        </text>
                                    </view> -->
                                    <view class="flex flex-1 items-center justify-between">
                                        <view class="text-[28rpx] font-500 price-font">{{ item.channelName }}:
                                            <text class="font-500 text-[36rpx] leading-none">￥</text>
                                            <text class="font-500 text-[36rpx] leading-none">{{
                                                item.refundPrice
                                                }}</text>
                                        </view>
                                        <view class="text-[28rpx] flex items-center font-500 price-font">

                                            {{ formData.way != 30 ? '退款金额:' : '撤销支付:' }}
                                            <!-- <template v-if="formData.refundType == 0">
                                                <text
                                                    class="font-500 text-[36rpx] text-[var(--price-text-color)] leading-none">￥</text>
                                                <input type="digit" v-model.number="item.refundPrice"
                                                    class="font-500 text-[36rpx] leading-none text-[var(--price-text-color)]"
                                                    :style="{ width: inputWidth(item.refundPrice) }"
                                                    @blur="handleInput">
                                            </template> -->
                                            <text class="font-500 text-[36rpx]  leading-none">￥</text>
                                            <text class="font-500 text-[36rpx]  leading-none">{{
                                                item.refundPrice
                                                }}</text>


                                        </view>
                                    </view>


                                </view>

                            </view>
                            <view class="text-left text-[24rpx] text-[var(--text-color-light9)] mt-[10rpx]">
                                当前显示的退款金额为系统根据原始订单自动核算的参考值。若需调整退款金额，可直接在对应输入框中填写您期望的退款数值，系统将以您填写的金额为准进行处理。
                            </view>
                        </view>

                    </view>

                    <view
                        class="my-[var(--top-m)] sidebar-margin px-[var(--pad-sidebar-m)] rounded-[var(--rounded-big)] bg-white"
                        v-if="formData.way != 30 && formData.refundType == 1">
                        <view class="py-[var(--pad-top-m)]">
                            <view class="flex items-center justify-between">

                                <view class="text-[28rpx] font-500">退款金额</view>
                                <view class="flex justify-end items-center text-[var(--price-text-color)] price-font">
                                    <text class="font-500 text-[36rpx] leading-none">￥</text>
                                    <input type="digit" v-model.number="formData.apply_money"
                                        class="font-500 text-[36rpx] leading-none"
                                        :style="{ width: inputWidth(formData.apply_money) }" @blur="handleInput">
                                    <!-- <text class="font-500 text-[36rpx] leading-none">{{
                                        diyGoods.fen2yuan(formData.apply_money
                                        )
                                    }}</text> -->
                                </view>
                            </view>
                            <view class="text-right text-[24rpx] text-[var(--text-color-light9)] mt-[10rpx]">
                                <text> 实际退款给会员的金额，请谨慎填写。</text>
                            </view>
                        </view>
                    </view>
                    <view
                        class="my-[var(--top-m)] sidebar-margin px-[var(--pad-sidebar-m)] rounded-[var(--rounded-big)] bg-white">
                        <view class="py-[var(--pad-top-m)] flex justify-between items-center">
                            <view class="text-[28rpx]"> <text class="font-500">申请员工</text>
                                <text class="text-[24rpx] text-[var(--text-color-light9)] ml-[10rpx]">必填</text>
                            </view>
                            <view class="flex ml-[auto] items-center h-[30rpx]" @click="refundCausePopup = true">
                                <text class="text-[26rpx]  truncate max-w-[460rpx]">{{
                                    currEmployeeName || '请选择' }}</text>
                                <text
                                    class="nc-iconfont nc-icon-youV6xx pt-[4rpx] text-[24rpx] text-[var(--text-color-light9)]"></text>
                            </view>

                        </view>
                    </view>
                    <view
                        class="my-[var(--top-m)] sidebar-margin px-[var(--pad-sidebar-m)] rounded-[var(--rounded-big)] bg-white">
                        <view class="py-[var(--pad-top-m)]">
                            <view class="text-[28rpx] flex items-center">
                                <text class="font-500">售后备注</text>
                                <text class="text-[24rpx] text-[var(--text-color-light9)] ml-[10rpx]">必填</text>
                            </view>
                            <view class="mt-[30rpx] h-[200rpx]">
                                <textarea class="leading-[1.5] h-[100%] w-[100%] text-[28rpx]" v-model="formData.remark"
                                    cols="30" rows="5" placeholder="补充描述,有助于更好的处理售后问题"
                                    placeholder-class="text-[26rpx] text-[var(--text-color-light9)]"></textarea>
                            </view>
                        </view>
                    </view>
                    <view class="w-full">
                        <view class="py-[var(--top-m)] px-[var(--sidebar-m)] box-border">
                            <button
                                class="primary-btn-bg !text-[#fff] h-[80rpx] leading-[80rpx] rounded-[100rpx] text-[26rpx] font-500"
                                :loading="operateLoading" @click="save">提交</button>
                        </view>
                    </view>

                    <!-- 申请员工 -->
                    <u-popup :show="refundCausePopup" @close="refundCausePopup = false">
                        <view class="popup-common" @touchmove.prevent.stop>
                            <view class="title">申请员工</view>
                            <scroll-view scroll-y="true" class="h-[450rpx] px-[30rpx] box-border">
                                <u-radio-group v-model="currEmployeeId" placement="column" iconPlacement="right">
                                    <u-radio activeColor="var(--primary-color)" :labelSize="'30rpx'" labelColor="#333"
                                        :customStyle="{ marginBottom: '34rpx' }" v-for="(item, index) in employeeList"
                                        :key="index" :label="item.employeeName" :name="item.employeeId"></u-radio>
                                </u-radio-group>
                            </scroll-view>
                            <view class="btn-wrap">
                                <button class="primary-btn-bg btn" @click="refundCausePopupFn">确定</button>
                            </view>
                        </view>
                    </u-popup>

                    <!-- 退款方式 -->
                    <u-popup :show="refundTypePopup" @close="refundTypePopup = false">
                        <view class="popup-common" @touchmove.prevent.stop>
                            <view class="title">退款方式 </view>
                            <scroll-view scroll-y="true" class="h-[450rpx] px-[30rpx] box-border">
                                <u-radio-group v-model="refundTypeId" placement="column" iconPlacement="right">
                                    <u-radio activeColor="var(--primary-color)" :labelSize="'30rpx'" labelColor="#333"
                                        :customStyle="{ marginBottom: '34rpx' }" v-for="(item, index) in refundTypeList"
                                        :key="index" :label="item.name" :name="item.id"></u-radio>
                                </u-radio-group>
                            </scroll-view>
                            <view class="btn-wrap">
                                <button class="primary-btn-bg btn" @click="refundTypePopupFn">确定</button>
                            </view>
                        </view>
                    </u-popup>
                </scroll-view>
            </swiper-item>
        </swiper>
    </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { redirect, img, moneyFormat, goback, deepClone } from '@/utils/common'
import { t } from '@/locale'
import { getRefundReason, adminRefundId, getRefundMoney } from '@/addon/shop/api/refund'
import { getSystemEmployeeList } from '@/app/api/employee'

import { uploadImage } from '@/app/api/system'
import { useSubscribeMessage } from "@/hooks/useSubscribeMessage";
import { skuSpecFormat, timeFormat, filterCardAttributes, fen2yuan, yuan2fen } from "@/utils/formatting"
import { useGoods } from '@/addon/shop/hooks/useGoods'
const diyGoods = useGoods();
const detail = ref(null)
const orderDetail = ref({})
const orderGoodsId = ref(0)
const step = ref(0)
const refundCausePopup = ref(false)
const formData = ref({
    order_id: detail.value?.order_id,
    order_goods_id: orderGoodsId.value,
    refundEmployee: undefined,//售后员工
    way: undefined,
    refundItems: [],
    reservProject: {
        bank: '', //支行信息
        bankBranch: '', //银行卡开户行
        bankHolder: '', //银行卡持有人
        bankPhone: '', //银行卡预留手机号
        bankCard: '' //银行卡号
    }, //银行卡信息
    apply_money: '',
    remark: '',
    payType: false, //退款账户类型
    refundType: 1 // 退款方式

})

const refundMoney = ref<any>({})
const currEmployeeId = ref('')
const currEmployeeName = computed(() => {
    return employeeList.value.find((item) => {
        return item.employeeId == formData.value.refundEmployee
    })?.employeeName
})

const refundTypePopup = ref(false)

const refundTypeList = ref<any>([{
    name: '原路退回',
    id: 0
}, {
    name: '退至余额',
    id: 1
}, {
    name: '退至银行卡/现金',
    id: 2
}])

const refundTypeId = ref(1)
const refundTypeName = computed(() => {

    return refundTypeList.value.find((item: any) => {
        return item.id == formData.value.refundType
    })?.name
})
const afterType = ref('') // 售后类型
/**
 * 选择单个商品
 */
const selectOnlyGoods = (data: any = {}) => {
    data.checked = !data.checked

}
onLoad((data) => {
    console.log(data)
    if (data.order_goods_id) {
        afterType.value = 'orderItem'
    } else {
        afterType.value = 'order'
    }
    orderGoodsId.value = data.order_goods_id || 0
    formData.value.order_goods_id = orderGoodsId.value
    formData.value.order_id = data.order_id || 0
    if (data.order_id) {
        getRefundMoney({ orderId: data.order_id }).then(({ data }) => {
            detail.value = data
            // detail.value.items.forEach((item, index) => {
            //     if (orderGoodsId.value == item.id) {
            //         orderDetail.value = item;
            //     }
            // })
            if (data?.refundItems) {
                data?.refundItems?.forEach((item: any) => {
                    item.checked = true
                    item.refundPrice = fen2yuan(item.refundPrice)
                })
            }
            formData.value.refundItems = data?.refundItems || []
            formData.value.apply_money = moneyFormat(fen2yuan(detail.value.payPrice))
        })


    } else {
        let parameter = {
            url: '/addon/shop/pages/order/list',
            title: '缺少订单id'
        };
        goback(parameter);
    }

})

const inputWidth = computed((value) => {
    return function (value) {
        if (value == '' || value == 0) {
            return '70rpx';
        } else {
            return String(value).length * 17 + 'rpx';
        }
    };
})

const selectRefundType = (type: number) => {
    formData.value.way = type
    step.value = 1
}



const operateLoading = ref(false)
const save = () => {
    if (!formData.value.refundEmployee) {
        uni.showToast({
            title: '请选择申请员工',
            icon: 'none'
        });
        return false;
    }
    if (!formData.value.remark) {
        uni.showToast({
            title: '请输入售后备注',
            icon: 'none'
        });
        return false;
    }

    // if ((Number(formData.value.apply_money).toFixed(2)) < 0) {
    //     uni.showToast({
    //         title: '退款金额不能为0,保留两位小数',
    //         icon: 'none'
    //     });
    //     return false;
    // }

    // if (Number(formData.value.apply_money) > Number(refundMoney.value.refund_money)) {
    //     uni.showToast({
    //         title: '退款金额不能大于可退款总额',
    //         icon: 'none'
    //     });
    //     return false;
    // }

    if (operateLoading.value) return
    operateLoading.value = true
    let data = deepClone(formData.value)
    let params = {
        orderId: data.order_id,
        way: data.way,
        refundType: data.way != 30 ? data.refundType : undefined,
        refundPrice: data.way != 30 ? yuan2fen(data.apply_money) : undefined,
        payType: data.way != 30 ? data.payType : undefined,

        applyReason: data.remark,
        refundEmployee: data.refundEmployee
    }
    adminRefundId(params).then((res) => {
        operateLoading.value = false
        setTimeout(() => {
            redirect({ url: '/addon/shop/pages/shopOrder/detail', param: { order_id: formData.value.order_id } })
        }, 1000)
    }).catch(() => {
        operateLoading.value = false
    })
}

const refundCausePopupFn = () => {

    formData.value.refundEmployee = currEmployeeId.value;
    refundCausePopup.value = false;
}
const refundTypePopupFn = () => {

    formData.value.refundType = refundTypeId.value;
    refundTypePopup.value = false;
}


const handleInput = (event: any) => {
    if (Number(event.detail.value) > Number(refundMoney.value.refund_money)) {
        uni.showToast({
            title: '退款金额不能大于可退款总额',
            icon: 'none'
        });
    }
}
const employeeList = ref<any>([])
const getEmployeeList = async () => {
    const { data } = await getSystemEmployeeList()
    employeeList.value = data
}
onMounted(() => {
    getEmployeeList()
})
</script>
<style lang="scss" scoped>
:deep(.u-upload__button) {
    width: 70px !important;
    height: 70px !important;
    border: 1px dashed #ddd;
    background-color: #fff;
    border-radius: 20rpx !important;
}

:deep(.u-upload__wrap__preview__image) {
    width: 70px !important;
    height: 70px !important;
}
</style>
